﻿/*******************************************************************************
 * Copyright © 2016-2020 北京网非科技有限公司 版权所有
 * Author: 北京网非科技有限公司
 * Description: 网非快速开发平台NET
 * Website：http://www.wfdot.com
*********************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using CubicFWNet.Common;
using CubicFWNet.Application.SystemManage;
using CubicFWNet.Application;
using CubicFWNet.Application.SystemSecurity;
using CubicFWNet.Data.SystemSecurity.Model;
using CubicFWNet.Data.SystemManage.Model;
using CubicFWNet.Mvc.Models;

namespace CubicFWNet.Mvc.Controllers
{
    public class LoginController : Controller
    {
        private ModuleApp _moduleApp;
        private const string LogType_LogIn = "登录";
        private const string LogType_LogIn_Failed = "登录失败";
        private const string LogType_LogIn_PwdFailed = "密码错误";
        private const string LogType_LogOut = "登出";

        public LoginController()
        {
            _moduleApp = new ModuleApp();
        }

        [HttpGet]
        public ViewResult Index()
        {
            return View();
        }
        [HttpGet]
        public ActionResult GetAuthCode()
        {
            return File(new VerifyCode().GetVerifyCode(), @"image/Gif");
        }
        [HttpGet]
        public async Task<ActionResult> OutLogin()
        {
            new LogApp().WriteDbLogAsync(new LogInLog
            {
                Type = LogType_LogOut,
                UserId = OperatorProvider.Provider.GetCurrent().UserId,
                UserName = OperatorProvider.Provider.GetCurrent().UserName,
                FamilyName = OperatorProvider.Provider.GetCurrent().FamilyName,
            });
            Session.Abandon();
            Session.Clear();
            OperatorProvider.Provider.RemoveCurrent();
            return RedirectToAction("Index", "Login");
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public async Task<ActionResult> CheckLogin(LogInViewModel loginModel)
        {
            if (!ModelState.IsValid)
            {
                return Content(new ResponseResult { Status = ResultType.error.ToString(), Message = this.GetFirstModelError() }.ToJson());
            }

            if (Session["cubic_session_verifycode"].IsEmpty() || Md5.md5(loginModel.Code.ToLower(), 16) != Session["cubic_session_verifycode"].ToString())
            {
                new LogApp().WriteDbLogAsync(
                    new LogInLog
                    {
                        Type = LogType_LogIn_Failed,
                        UserId = Guid.NewGuid(),    //新生成一个，要不数据库主键为空或者重复会抛异常
                        UserName = loginModel.UserName,
                        Memo = "验证码错误"
                    });
                return Content(new ResponseResult { Status = ResultType.error.ToString(), Message = "验证码错误，请重新输入" }.ToJson());
            }

            ResponseResult result = new UserApp().CheckLogin(loginModel.UserName, loginModel.Password);
            if (result.Status == LoginResult.success.ToString()) //登录成功
            {
                User user = (User)result.Data;
                OperatorModel operatorModel = new OperatorModel
                {
                    UserId = user.Id,
                    UserName = user.UserName,
                    FamilyName = user.FamilyName,
                    LoginIPAddress = Net.Ip,
                    //LoginIPAddressName = Net.GetLocation(operatorModel.LoginIPAddress),
                    LoginTime = DateTime.Now,
                    LoginToken = DESEncrypt.Encrypt(Guid.NewGuid().ToString())
                };

                if (user.UserName == "admin")
                {
                    operatorModel.IsSystem = true;
                }
                else
                {
                    operatorModel.IsSystem = false;
                }
                OperatorProvider.Provider.AddCurrent(operatorModel);
                new LogApp().WriteDbLogAsync(
                    new LogInLog
                    {
                        Type = LogType_LogIn,
                        UserId = user.Id,
                        UserName = user.UserName,
                        FamilyName = user.FamilyName
                    });
            }
            else if (result.Status == LoginResult.password_error.ToString())
            {
                User user = (User)result.Data;
                new LogApp().WriteDbLogAsync(
                       new LogInLog
                       {
                           Type = LogType_LogIn_PwdFailed,
                           UserId = user.Id,
                           UserName = user.UserName,
                           FamilyName = user.FamilyName,
                           Memo = result.Message
                       });
                //检测当天密码错误是否大于6次
                new LogApp().PasswordErrorUpdateUserStatus(user.Id);
            }
            else   //登录失败
            {
                new LogApp().WriteDbLogAsync(
                    new LogInLog
                    {
                        Type = LogType_LogIn_Failed,
                        UserId = Guid.NewGuid(),   //新生成一个，要不数据库主键为空或者重复会抛异常
                        UserName = loginModel.UserName,
                        Memo = result.Message
                    });
            }
            return Content(result.ToJson());
        }
    }
}